import React, { useState, useEffect } from 'react';
import { Table, Button, Space, Tag, Modal, message, Tabs } from 'antd';
import { roleStore } from './store/roleStore';
import { rolePermissionStore } from './store/rolePermission';
import { roleUserStore } from './store/roleUserStore';
import { observer } from 'mobx-react-lite';
import { PlusOutlined, EditOutlined, DeleteOutlined, EyeOutlined, UserAddOutlined } from '@ant-design/icons';
import { useNavigate } from 'react-router-dom';
import RoleForm from './components/RoleForm';
import FunctionForm from './components/RolePermissionForm';
import RoleUserForm from './components/RoleUserForm';
import { Role, RolePermission, RoleUser } from './store/types';

const { TabPane } = Tabs;

export type ActiveType = 'role' | 'function' | 'user';

const RoleList: React.FC = observer(() => {
  const navigate = useNavigate();
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [editingItem, setEditingItem] = useState<Role | RolePermission | RoleUser | null>(null);
  const [modalType, setModalType] = useState<'create' | 'edit' | 'view'>('create');
  const [activeTab, setActiveTab] = useState<ActiveType>('role');

  // 根据标签页获取数据
  useEffect(() => {
    switch (activeTab) {
      case 'role':
        roleStore.fetchRoles();
        roleUserStore.getActiveRole();
        roleUserStore.getActiveUser();
        rolePermissionStore.getActivePermission();
        break;
      case 'function':
        roleUserStore.getActiveRole();
        rolePermissionStore.getActivePermission();
        rolePermissionStore.fetchRolePermissions();
        break;
      case 'user':
        roleUserStore.getActiveRole();
        roleUserStore.getActiveUser();
        roleUserStore.fetchRoleUsers();
        break;
    }
  }, [activeTab]);

  // 通用列配置
  const commonColumns = [
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      render: (status: string) => (
        <Tag color={status === 'active' ? 'success' : 'error'}>
          {status === 'active' ? '启用' : '禁用'}
        </Tag>
      ),
    },
  ];


  const renderRole = (roleId: string) => {
    const roleMap = roleUserStore.roleValues;
    const config = roleMap && roleMap[roleId as keyof typeof roleMap];
    return config ? <Tag color={config.color}>{config.title}</Tag> : null;
  };

  const renderUser = (userId: string) => {
    const userMap = roleUserStore.userValues;
    const config = userMap && userMap[userId as keyof typeof userMap];
    return config ? <span >{config.title}</span> : null;
  };

  const renderPermission = (permissionId: string) => {
    const permissionMap = rolePermissionStore.permissionValues;
    const config = permissionMap && permissionMap[permissionId as keyof typeof permissionMap];
    return config ? <Tag color={config.color}>{config.title}</Tag> : null;
  };

  // 角色列
  const roleColumns = [
    { title: '角色名称', dataIndex: 'roleName', key: 'roleName' },
    { title: '角色编码', dataIndex: 'roleCode', key: 'roleCode' },
    // { title: '描述', dataIndex: 'description', key: 'description'},
    
    ...commonColumns,
    {
      title: '操作',
      key: 'action',
      render: (_: any, record: Role) => renderActions(record),
    },
  ];

  
  // 功能权限列
  const functionColumns = [
    { title: '角色', dataIndex: 'roleId', key: 'roleId', render: (_: any, record: RolePermission) => renderRole(record.roleId)},
    { title: '权限项', dataIndex: 'permissionId', key: 'permissionId', render: (_: any, record: RolePermission) => renderPermission(record.permissionId) },
    {
      title: '操作',
      key: 'action',
      render: (_: any, record: RolePermission) => renderActions(record),
    },
  ];

  // 成员列
  const userColumns = [
    { title: '用户', dataIndex: 'userId', key: 'userId' , render: (_: any, record: RoleUser) => renderUser(record.userId)},
   { title: '角色', dataIndex: 'roleId', key: 'roleId', render: (_: any, record: RoleUser) => renderRole(record.roleId)},
    {
      title: '操作',
      key: 'action',
      render: (_: any, record: RoleUser) => renderActions(record),
    },
  ];

  // 通用操作渲染
  const renderActions = (record: any) => (
    <Space size="middle">
      <Button
        type="link"
        icon={<EyeOutlined />}
        onClick={() => handleView(record)}
      >
        查看
      </Button>
      <Button
        type="link"
        icon={<EditOutlined />}
        onClick={() => handleEdit(record)}
      >
        编辑
      </Button>
      <Button
        type="link"
        danger
        icon={<DeleteOutlined />}
        onClick={() => handleDelete(record)}
      >
        删除
      </Button>
    </Space>
  );

  // 获取当前数据源
  const getDataSource = () => {
    switch (activeTab) {
      case 'role': return roleStore.roles;
      case 'function': return rolePermissionStore.functions;
      case 'user': return roleUserStore.users;
      default: return [];
    }
  };

  // 获取当前列配置
  const getColumns = () => {
    switch (activeTab) {
      case 'role': return roleColumns;
      case 'function': return functionColumns;
      case 'user': return userColumns;
      default: return [];
    }
  };

  const handleCreate = () => {
    setModalType('create');
    setEditingItem(null);
    setIsModalVisible(true);
  };

  const handleEdit = (record: any) => {
    setModalType('edit');
    fetchItemDetails(record);
  };

  const handleView = (record: any) => {
    setModalType('view');
    fetchItemDetails(record);
  };

  const fetchItemDetails = async (record: any) => {
    try {
      let data;
      switch (activeTab) {
        case 'role':
          data = await roleStore.getRole(record.id);
          break;
        case 'function':
          data = await rolePermissionStore.getRolePermission(record.id);
          break;
        case 'user':
          data = await roleUserStore.getUser(record.id);
          break;
      }
      setEditingItem(data);
      setIsModalVisible(true);
    } catch (error) {
      message.error('获取详情失败');
    }
  };

  const handleDelete = (record: any) => {
    Modal.confirm({
      title: '确认删除',
      content: `确定要删除当前项吗？`,
      okText: '确定',
      cancelText: '取消',
      onOk: () => {
        switch (activeTab) {
          case 'role':
            roleStore.deleteRole(record.id);
            break;
          case 'function':
            rolePermissionStore.deleteRolePermission(record.id);
            break;
          case 'user':
            roleUserStore.deleteUser(record.id);
            break;
        }
        
        message.success('删除成功');
      },
    });
  };

  const renderForm = () => {
    switch (activeTab) {
      case 'role':
        return <RoleForm type={modalType} initialValues={editingItem} onCancel={() => setIsModalVisible(false)} />;
      case 'function':
        return <FunctionForm type={modalType} initialValues={editingItem} onCancel={() => setIsModalVisible(false)} />;
      case 'user':
        return <RoleUserForm type={modalType} initialValues={editingItem} onCancel={() => setIsModalVisible(false)} />;
    }
  };

  const getModalTitle = () => {
    const titles = {
      role: '角色',
      function: '功能权限',
      user: '用户'
    };
    return `${modalType === 'create' ? '新建' : modalType === 'edit' ? '编辑' : '查看'}${titles[activeTab]}`;
  };

  return (
    <div>
      <div style={{ 
        padding: '16px 24px',
        background: '#fff',
        borderBottom: '1px solid #f0f0f0',
        zIndex: 1
      }}>
        <Tabs
          activeKey={activeTab}
          onChange={(key) => setActiveTab(key as ActiveType)}
          style={{ marginBottom: 16 }}
        >
          <TabPane tab="角色信息" key="role" />
          <TabPane tab="功能权限" key="function" />
          <TabPane tab="成员设置" key="user" />
        </Tabs>

        <Button
          type="primary"
          icon={activeTab === 'user' ? <UserAddOutlined /> : <PlusOutlined />}
          onClick={handleCreate}
        >
          {activeTab === 'role' && '新建角色'}
          {activeTab === 'function' && '新建权限'}
          {activeTab === 'user' && '添加成员'}
        </Button>
      </div>

      <Table
        columns={getColumns() as any}
        dataSource={getDataSource() as any}
        rowKey="id"
        locale={{ emptyText: '暂无数据' }}
        loading={
          activeTab === 'role' ? roleStore.loading :
          activeTab === 'function' ? rolePermissionStore.loading :
          roleUserStore.loading
        }
      />

      <Modal
        title={getModalTitle()}
        open={isModalVisible}
        onCancel={() => setIsModalVisible(false)}
        footer={null}
        width={800}
        destroyOnClose
      >
        {renderForm()}
      </Modal>
    </div>
  );
});

export default RoleList;